<template>
	<view class="bg-gray">
		<cu-custom :isBack="true">
		</cu-custom>
		<view :style="[{top:customBarHeight + 'px'}]">
			<view class="bg-white nav">
				<view class="flex text-center common-bar-height">
					<view class="cu-item flex-sub">
						<picker @change="statusChange" :value="statusIndex" :range='statusList' range-key="label">
							<view class="text-df">
								{{formatStatusIndex(statusIndex).label}}
							</view>
						</picker>
					</view>
					<view class="cu-item flex-sub">
						<picker mode="multiSelector" @change="productAndSeriesChange"
							@columnchange="productAndSeriesColumnchange" :value="productAndSeriesIndex"
							:range='productAndSeriesNameList'>
							<view class="text-df">
								{{productAndSeriesNameList[0][productAndSeriesIndex[0]]}} [
								{{productAndSeriesNameList[1][productAndSeriesIndex[1]]}} ]
							</view>
						</picker>
					</view>
				</view>
			</view>
			<view class=" flex justify-between">
				<view class="bg-white" style="width:33%;height:100%;">
					<view id="areaModel" class="cu-bar bg-white solid-bottom">
						<view class="action">
							<text class="cuIcon-titles text-orange"></text>{{$t('area')}}
						</view>
					</view>
					<scroll-view scroll-y :style="style">
						<view class="ztnCustom-provinceBlock" v-for="(item,index) in provinceList" :key="index">
							<view @tap="showCityModal(item)" class="cu-bar bg-white"
								:class="[provinceId === item.provinceId ? 'bg-gray':'bg-white']">
								<view class="action">
									{{item.province}}
								</view>
							</view>
						</view>
					</scroll-view>
				</view>

				<view class="bg-white" style="width:66%;height:100%">
					<view class="cu-bar bg-white">
						<view class="action">
							<!-- {{$t('number')}} : {{cityTotal}} -->
							<text class="text-grey">{{city}}</text>
						</view>
					</view>
					<scroll-view @scrolltolower="scrolltolower" scroll-y :style="style">
						<view class="margin-top-xs" v-for="(arrItem,arrIndex) in deviceList" :key="arrIndex">
							<view v-for="(item,index) in arrItem" :key="index">
								<view class="flex justify-start align-center margin-bottom">
									<surplus class="surplus margin-right-sm margin-left-sm" id="surplus"
										:surplus="item.surplus">
									</surplus>
									<view class="text-df"
										@tap='deviceNavigation(item.deviceName,item.deviceCore,"deviceSensor")'
										:style="{color : item.status === 'ONLINE' ? '#67c23a' :'#aaaaaa'}">
										{{item.deviceName}}
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<view v-if="cityModal"
			style="position:fixed;left:0;bottom:0;width:100%;height:100%;background: rgba(0, 0, 0, 0.6);z-index: 1024">
			<view class="bg-white padding-bottom "
				style="position:fixed;width:100%;bottom:0;z-index: 1024;border-top-left-radius:20rpx;border-top-right-radius:20rpx">
				<view class="flex justify-between">
					<view class="margin lg" @tap="hideCityModal">{{$t('cancel')}}</view>
				</view>
				<view class="flex justify-start flex-wrap">
					<view class="margin margin-bottom-xs" v-for="(item,index) in cityList" :key="index">
						<button @tap="selectCity(item)" class="cu-btn block lg"
							:class="cityId == item.cityId ? 'bg-grey' : 'line-grey'">{{item.city}}</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showToast
	} from '@/util/toast.js'
	import {
		listDeviceStatus,
		listProductSeries,
		listProductList
	} from '@/util/utils.js'
	import * as iotDeviceApi from '@/api/iot/iotDeviceApi.js'
	import * as storage from '@/util/storage.js'
	import *
	as iotDeviceBelongApi from '@/api/iot/iotDeviceBelongApi.js'
	import * as iotProductApi from '@/api/iot/iotProductApi.js'
	import * as iotProductSeriesApi from '@/api/iot/iotProductSeriesApi.js'
	import * as iotProductUserApi from '@/api/iot/iotProductUserApi.js'
	import * as iotProductSeriesUserApi from '@/api/iot/iotProductSeriesUserApi.js'
	import Surplus from '@/components/ztn-custom/Surplus/index.vue'
	export default {
		data() {
			return {
				customBarHeight: storage.getCustomBarHeight(),
				style: '',
				provinceList: [],
				provinceId: '',
				cityModal: false,
				cityList: [],
				cityId: Number,
				city: '',
				currentPage: 1,
				pageSize: 30,
				deviceList: [],
				hasMoreData: true,
				productList: [],
				productSeriesList: [],
				productAndSeriesList: [
					[],
					[]
				],
				productAndSeriesNameList: [
					[],
					[]
				],
				productPageList: [],
				statusIndex: 0,
				statusList: [],
				productAndSeriesIndex: [0, 0],
				productId: null,
				seriesId: null,
				userId: storage.getUserId(),
				companyId: storage.getCompanyId(),
				deptId: storage.getDeptId(),
				websiteModel: storage.getWebsiteModel()
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		props: {
			currentProductId: {
				type: [Number, String],
				default: null
			},
		},
		onReady() {
			const screenHeight = storage.getScreenHeight()
			const areaHeight = storage.getAreaHeight()
			if (areaHeight) {
				this.style = `height:${screenHeight - areaHeight - this.customBarHeight}px`
			} else {
				uni.createSelectorQuery().select('#areaModel').boundingClientRect((e) => {
					this.style = `height:${screenHeight - e.height - this.customBarHeight}px`
					storage.setAreaHeight(e.height)
				}).exec()
			}
		},
		onShow() {
			this.init()
		},
		methods: {
			formatStatusIndex(index) {
				return this.statusList[index]
			},
			init() {
				this.statusList = listDeviceStatus(this)
				this.statusIndex = storage.getStatusIndex() || 0
				if (this.currentProductId) {
					this.productId = parseInt(this.currentProductId)
				}
				this.listProductAndSeries().then(res => {
					this.productAndSeriesList = [this.productList, this.productSeriesList]
					const index = this.productList.findIndex((item) => item.productId === this.productId)
					this.productAndSeriesIndex = [index, 0]
				})
				this.getProvinceList()
			},
			handleProductSeriesList(data) {
				this.productSeriesList = listProductSeries(this, data)
				this.makeProductAndSeriesNameList()
			},
			listProductAndSeries: async function() {
				let api
				switch (this.websiteModel) {
					case 'system':
					case 'company':
					case 'dept':
						api = iotProductApi.listProduct({})
						break
					default:
						api = iotProductUserApi.listProduct({
							userId: this.userId
						})
				}

				await api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.productList = listProductList(this, data)
					}
				})
				if (this.productId) {
					await this.listSeries();
				} else {
					this.handleProductSeriesList([])
				}
			},
			listSeries() {
				return new Promise((resolve, reject) => {
					let api
					switch (this.websiteModel) {
						case 'system':
						case 'company':
						case 'dept':
							api = iotProductSeriesApi.listSeries({
								productId: this.productId
							})
							break
						default:
							api = iotProductSeriesUserApi.listSeries({
								userId: this.userId,
								productId: this.productId
							})
					}
					api.then((res) => {
						const {
							data
						} = res
						if (data) {
							this.handleProductSeriesList(data)
							resolve()
						}
					})
				})
			},
			makeProductAndSeriesNameList() {
				const productNameList = []
				this.productList.forEach(item => {
					productNameList.push(item.name)
				})
				const productSeriesNameList = []
				this.productSeriesList.forEach(item => {
					productSeriesNameList.push(item.name)
				})
				this.productAndSeriesNameList = [productNameList, productSeriesNameList]
			},
			statusChange(e) {
				this.statusIndex = e.detail.value
				storage.setStatusIndex(this.statusIndex)
				this.currentPage = 1
				this.deviceList = []
				this.pageGetDevice()
			},
			productAndSeriesColumnchange(e) {
				const column = e.detail.column
				const value = e.detail.value
				switch (column) {
					case 0: //拖动第1列
						if (value != 0) {
							this.productId = this.productList[value].productId
							this.listSeries().then((res) => {
								this.productAndSeriesIndex = [value, 0]
							})
						} else {
							this.productAndSeriesIndex = [0, 0]
						}
						break;
					case 1:
						this.productAndSeriesIndex = [this.productAndSeriesIndex[0], value]
						break
					default:
						break;
				}
				// this.$forceUpdate()
				this.pageGetDevice()
			},
			productAndSeriesChange(e) {
				const index = e.detail.value
				this.productAndSeriesIndex = index
				this.productId = this.productList[index[0]].productId
				this.seriesId = this.productSeriesList[index[1]].seriesId
				this.currentPage = 1
				this.deviceList = []
				this.pageGetDevice()
			},
			getProvinceList() {

				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listProvinceNumAll({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
						})
						break
					case 'company':
						api = iotDeviceApi.listProvinceNumByCompany({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
						})
						break
					case 'dept':
						api = iotDeviceApi.listProvinceNumByDept({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
						})
						break
					default:
						api = iotDeviceBelongApi.listProvinceNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
						})
				}


				api.then((res) => {
					if (res.data) {
						let data = res.data
						let list = []
						for (let index = 0; index < data.length; index++) {
							let {
								province,
								provinceId
							} = data[index];
							list.push({
								province,
								provinceId
							})
						}
						this.provinceList = list
						this.provinceId = list[0].provinceId
						this.getCityList(true)
					}
				})
			},
			getCityList(first) {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listCityNumAll({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							provinceId: this.provinceId
						})
						break
					case 'company':
						api = iotDeviceApi.listCityNumByCompany({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							provinceId: this.provinceId
						})
						break
					case 'dept':
						api = iotDeviceApi.listCityNumByDept({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							provinceId: this.provinceId
						})
						break
					default:
						api = iotDeviceBelongApi.listCityNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							provinceId: this.provinceId
						})
				}

				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						const list = []
						for (let index = 0; index < data.length; index++) {
							const {
								cityId,
								city
							} = data[index];
							list.push({
								cityId,
								city,
							})
						}
						this.cityList = list
						if (first) {
							const {
								cityId,
								city
							} = list[0]
							this.cityId = cityId
							this.city = city
							this.pageGetDevice()
						}
					}
				})
			},
			pageGetDevice() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.pageGetAllDevice({
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'company':
						api = iotDeviceApi.pageGetCompanyDevice({
							companyId: this.companyId,
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'dept':
						api = iotDeviceApi.pageGetDeptDevice({
							deptId: this.deptId,
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					default:
						api = iotDeviceBelongApi.pageGetDevice({
							provinceId: this.provinceId,
							cityId: this.cityId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
				}

				api.then((res) => {
					if (res.data) {
						const {
							currentPage,
							data,
							total
						} = res.data
						const lastPage = Math.ceil(total / this.pageSize)
						this.$set(this.deviceList, currentPage - 1, data)
						this.hasMoreData = lastPage >= currentPage ? true : false
						this.currentPage = currentPage + 1
					}
				})
			},
			showCityModal(provinceItem) {
				const provinceId = provinceItem.provinceId
				this.provinceId = provinceId
				this.getCityList(false)
				this.cityModal = true
			},
			hideCityModal() {
				this.cityModal = false
			},
			selectCity(cityItem) {
				this.city = cityItem.city
				this.cityId = cityItem.cityId
				this.deviceList = []
				this.currentPage = 1
				this.pageGetDevice()
				this.hideCityModal()
			},
			deviceNavigation(deviceName, deviceCore, component) {
				uni.navigateTo({
					url: `/pages/deviceNavigation/deviceNavigation?deviceName=${deviceName}&deviceCore=${deviceCore}&component=${component}`
				})
			},
			scrolltolower() {
				this.hasMoreData ? this.pageGetDevice() : showToast(this.$t('not') + this.$t('data'), 'none', 1000, false)
			}
		},
		components: {
			Surplus
		},
		onShareAppMessage(res) {
			const nickName = storage.getNickName()
			const shortCompanyName = storage.getShortCompanyName()
			return {
				title: `${nickName}${this.$t('share')}${shortCompanyName}`,
				path: '/pages/areaList/areaList',
				success: (res) => {}
			}
		}
	}
</script>

<style>
	page {
		background-color: #f8f8f8;
	}
</style>
